<template>
	<a-modal
		:visible="props.visible"
		:title="props.type === 'new' ? '新增标签组' : '编辑标签组'"
		:width="400"
		@cancel="emits('update:visible', false)"
		@ok="onSubmit"
		:confirmLoading="onLoading"
	>
		<a-form ref="formRef" :model="form" :rules="rules" :label-col="{ style: { width: '100px' } }">
            <a-form-item label="标签组名称" name="groupName">
                <a-input v-model:value="form.groupName" showCount :maxlength="10"></a-input>
            </a-form-item>
            <a-form-item label="适用对象" name="groupType">
                <a-checkbox-group v-model:value="form.groupType" 
					name="checkboxgroup" 
					:disabled="props.type==='edit'"
					:options="[
						{ label: '客户', value: '0' },
						{ label: '线索', value: '1' }
					]" />
            </a-form-item>
		</a-form>
	</a-modal>
</template>
<script setup>

	const props = defineProps({
		visible: {
			type: Boolean,
			default: false
		},
		type: {
			type: String
		},
		callBack: {
			type: Function
		},
		info: {
			type: Object
		}
	})
	const emits = defineEmits(['update:visible', 'finished'])

	onBeforeMount(() => {
		if (props.type === 'new') {
			form.value = { ...defaultForm }
		} else {
			form.value.id = props.info.id
			form.value.groupName = props.info.groupName
			form.value.groupType = props.info.groupType ? props.info.groupType.split(',') : null
		}
	})

	/**
	 * 添加表单逻辑
	 */
	const defaultForm = {
		groupName: undefined,
		groupType: undefined,
	}
	const form = ref({})
	const rules = {
		groupName: [{ required: true, message: '请输入标签组名称', trigger: 'blur' }],
		groupType: [{ required: true, message: '请选择适用对象', trigger: 'change' }],
	}

	const formRef = ref()
	const onLoading = ref(false)
	const onSubmit = () => {
		formRef.value.validate().then(() => {
			const { groupType, ...other } = form.value
			onLoading.value = true
			props
				.callBack({ ...other, groupType: groupType.join(',') }, props.type==='edit')
				.then(() => {
					onLoading.value = false
					emits('update:visible', false)
					emits('finished')
				})
				.finally(() => {
					onLoading.value = false
				})
		})
	}
</script>
<style lang="less" scoped>
	:deep(.ant-form-item-label > label) {
		white-space: initial;
		height: 36px;
	}
</style>
